/**
 * Copying (c) Qixin Technoligies Co.,Ltd.2019-2029.all rights reserved.
 */

package com.example.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.websocket.server.PathParam;
import java.util.Collections;

/**
 * 创  建   时  间： 2020/8/4
 * 版           本: V1.0
 * 作           者: qixin
 * 版  权   所  有: 版权所有(C)2019-2029
 * 公           司: 深圳市七智星科技有限公司
 */
@RestController
public class ParamRuleController {
    private String resourceName = "sayHello";

    /**
     * 热点参数限流的使用
     * @param id
     * @param name
     * @return
     */
    @GetMapping("/hello")
    public String sayHello(@PathParam("id") String id,@PathParam("name") String name){
        Entry entry = null;
        try{
            entry = SphU.entry(resourceName,EntryType.IN,1,id);
            return "access success";
        }catch (BlockException e){
            e.printStackTrace();
            return "block";
        }finally {
            if(entry!=null){
                entry.exit();
            }
        }
    }

    @PostConstruct
    public void initParamRule(){
        ParamFlowRule rule = new ParamFlowRule(resourceName);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(1);
        // rule.setDurationInSec() 统计窗口时间长度，单位为秒
        // rule.setMaxQueueingTimeMs() 最长排队等侍时长，只有当流控行为controlBehavior设置为匀速排队模式时生效
        // rule.setParamIdx(0); 热点参数索引，属于必填项，它对应的是SphU.entry(XXX,args)中的参数索引位置
        // rule.setParamFlowItemList() 针对指定参数值单独设置限流阈值，不受count阈值的限制
        ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
    }

    @SentinelResource
    @GetMapping("/helloworld")
    public String helloworld(@PathParam("id") String id){

        return "access success";
    }
}
